package com.tiancheng.trade.payment.mq.consumer;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tiancheng.trade.commom.core.data.MessageBody;
import com.tiancheng.trade.commom.core.data.Result;
import com.tiancheng.trade.commom.core.enums.PaymentChannelEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.payment.bo.meesage.PaymentCommonMessageBO;
import com.tiancheng.trade.payment.channel.bo.GetRefundOrderResBO;
import com.tiancheng.trade.payment.channel.bo.GetUnifiedOrderResBO;
import com.tiancheng.trade.payment.channel.bo.PayResultBO;
import com.tiancheng.trade.payment.channel.bo.RefundResultBO;
import com.tiancheng.trade.payment.channel.enums.ChannelOrderStatusEnum;
import com.tiancheng.trade.payment.enums.FlowStatusEnum;
import com.tiancheng.trade.payment.mq.PaymentCenterMsgProducer;
import com.tiancheng.trade.payment.service.NotifyService;
import com.tiancheng.trade.payment.service.PaymentOrderService;
import com.tiancheng.trade.payment.service.PaymentRefundService;
import com.tiancheng.trade.payment.util.cache.PaymentCache;
import com.tiancheng.trade.payment.vo.api.GetRefundOrderVo;
import com.tiancheng.trade.payment.vo.api.GetUnifiedOrderVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author kellen
 * @description 取消订单消息的处理者
 * @date 2025/02/25 23:39
 */
@Component
@RabbitListener(queues = "trade.payment.common.message")
@Slf4j
public class PaymentCommonQueueConsumer {

    @Resource
    private PaymentOrderService paymentOrderService;
    @Resource
    private PaymentRefundService paymentRefundService;
    @Resource
    private PaymentCenterMsgProducer paymentCenterMsgProducer;
    @Resource
    private NotifyService notifyService;

    @RabbitHandler
    public void handle(String message) throws Exception {
        MessageBody messageBody = JsonUtil.fromJson(message, MessageBody.class);
        if (Objects.isNull(messageBody) || Objects.isNull(messageBody.getData())) {
            log.warn("订单中心延时处理队列，消息内容为空！");
            return;
        }
        PaymentCommonMessageBO messageBO = JsonUtil.fromJson(JsonUtil.toJsonString(messageBody.getData()), PaymentCommonMessageBO.class);
        log.info("订单中心延时处理队列:{}", messageBO);
        if (Objects.isNull(messageBO) || StringUtils.isEmpty(messageBO.getMessageBody())) {
            log.warn("订单中心延时处理队列，消息内容为空！");
            return;
        }
        try {
            messageHandler(messageBO);
        } catch (Exception e) {
            log.error("支付中心消息处理异常：", e);
            throw e;
        }
    }

    private void messageHandler(PaymentCommonMessageBO messageBO) {
        switch (messageBO.getMessageType()) {
            case trade_payment_common_query_pay_result:
                // 查询支付结果信息
                final GetUnifiedOrderVo params = JsonUtil.fromJson(messageBO.getMessageBody(), GetUnifiedOrderVo.class);
                if (params == null || StringUtils.isEmpty(params.getFlowId()) || PaymentCache.getCachePaymentStatusQueryParams(params.getFlowId()).isEmpty()) {
                    log.info("查询订单支付状态，参数为空或订单状态以改变，完结！");
                    return;
                }
                // 判断重试次数
                if (messageBO.getCurrentRetryPosition() > messageBO.getRetryCount()) {
                    log.warn("查询订单状态结束，已超过最大重试次数,订单id：{}", params.getFlowId());
                    return;
                }

                Result<GetUnifiedOrderResBO> result = paymentOrderService.queryPayResult(params);
                if (result.getRet() != 0) {
                    // 再次发起
                    messageBO.setCurrentRetryPosition(messageBO.getCurrentRetryPosition() + 1);
                    paymentCenterMsgProducer.setPaymentQueryMsg(messageBO);
                    return;
                }
                if (result.getData().getOrderStatus().equals(ChannelOrderStatusEnum.success) || result.getData().getOrderStatus().equals(ChannelOrderStatusEnum.fail)) {
                    // 支付成功了，推送业务系统一次？
                    // 直接走回调处理service
                    // 构建支付成功通知
                    final PayResultBO bo = new PayResultBO();
                    bo.setOrderId(params.getFlowId());
                    bo.setAmount(result.getData().getAmount());
                    bo.setPayTime(LocalDateTime.now());
                    bo.setStatus(result.getData().getOrderStatus().name());
                    bo.setCouponAmount(0);
                    bo.setTradeNo(result.getData().getTradeNo());
                    notifyService.mockPayNotify(bo);
                    // 删除掉缓存
                    PaymentCache.delCachePaymentStatusQueryParams(params.getFlowId());
                    return;
                }
                // 再次发起
                messageBO.setCurrentRetryPosition(messageBO.getCurrentRetryPosition() + 1);
                paymentCenterMsgProducer.setPaymentQueryMsg(messageBO);
                break;
            case trade_payment_common_query_refund_result:
                // 查询退款结果信息
                final GetRefundOrderVo queryRefundParams = JsonUtil.fromJson(messageBO.getMessageBody(), GetRefundOrderVo.class);
                Result<GetRefundOrderResBO> queryRefundResult = paymentRefundService.queryRefundStatus(queryRefundParams.getFlowId());
                if (queryRefundResult.getRet() != 0) {
                    // 再次发起
                    messageBO.setCurrentRetryPosition(messageBO.getCurrentRetryPosition() + 1);
                    paymentCenterMsgProducer.setPaymentQueryMsg(messageBO);
                    return;
                }
                if (Objects.nonNull(queryRefundResult.getData()) && (queryRefundResult.getData().getChannelOrderStatusEnum().equals(ChannelOrderStatusEnum.success)
                        || queryRefundResult.getData().getChannelOrderStatusEnum().equals(ChannelOrderStatusEnum.fail))) {
                    // 支付成功了，推送业务系统一次？
                    // 直接走回调处理service
                    // 构建支付成功通知
                    final RefundResultBO bo = new RefundResultBO();
                    bo.setRefundId(queryRefundResult.getData().getRefundId());
                    bo.setAmount(0);
                    bo.setRefundAmount(queryRefundResult.getData().getAmount());
                    bo.setRefundTime(LocalDateTime.now());
                    bo.setStatus(queryRefundResult.getData().getChannelOrderStatusEnum().name());
                    bo.setPaymentChannel(PaymentChannelEnum.getByCode(queryRefundResult.getData().getPaymentChannel()).get());
                    bo.setPayFlowId(queryRefundResult.getData().getPayFlowId());
                    notifyService.mockRefundNotify(bo);
                    // 删除掉缓存
                    PaymentCache.delCachePaymentStatusQueryParams(queryRefundResult.getData().getRefundId());
                    return;
                }
                // 再次发起
                messageBO.setCurrentRetryPosition(messageBO.getCurrentRetryPosition() + 1);
                paymentCenterMsgProducer.setPaymentQueryMsg(messageBO);
                break;
        }
    }
}
